import { useMutation, useQuery } from 'react-query';
import { request, TResData } from '@/request';
import { TJob } from '@/types';
import { JobEditor } from '@/components';
import { useParams, useHistory } from 'react-router-dom';

const JobEdit = () => {
   let { id } = useParams();
   let history = useHistory();
   const { data } = useQuery<TResData<TJob>>('job', () =>
      request<TJob>(`/jobs/${id}`)
   );

   const updateJob = useMutation(
      (job: TJob) =>
         request<TJob>(`/jobs/${id}`, {
            method: 'PATCH',
            data: job,
            showSuccess: true,
         }),
      {
         onSuccess: () => {
            history.push('/jobs');
         },
      }
   );

   const handleSubmit = (data: TJob) => {
      updateJob.mutate({
         company: data.company,
         position: data.position,
         location: data.location,
         status: data.status,
         jobType: data.jobType,
      });
   };

   if (!data) return <div>Loading...</div>;

   return (
      <JobEditor submitTxt="Save" onSubmit={handleSubmit} data={data.data} />
   );
};

export default JobEdit;
